﻿//==================================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-04-22
// 描 述：页面基类，所有的aspx页面继承自基类
//        页面基类提供常用的方法和常用的用户信息
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人       修改内容
// 1.00   2015/4/22   江怀玉           
//==================================================================
using System;
using System.IO;
using System.Web;
using System.Collections.Specialized;
using FL.Bussiness;
using FL.DBModule.Sys;
using FL.Common;
using System.Text.RegularExpressions;

namespace FL.Web.BackEnd
{
    public class BasePage : System.Web.UI.Page
    {
       
        public string SystemName
        {
            get
            {
                return AppSettingsHelper.GetString("SystemName");
            }
        }

        public string DevCommpay
        {
            get
            {
                return AppSettingsHelper.GetString("DevCommpay");
            }
        }
        /// <summary>
        /// 实体类名[对应表名]
        /// </summary>
        public virtual string EntityName
        {
            get
            {
                return GetStringFromQueryString("entity", "");
            }
        }

        /// <summary>
        /// 
        /// </summary>
         public BaseBussnies _bll = null;
        public void CreateBussniess(string entityName)
        {
            if (string.IsNullOrEmpty(entityName))
            {
                _bll = new BaseBussnies();
                //return _bll;
            }
            else
            {
                this._bll = BaseBussnies.CreateInstance(entityName);
            }
        }

        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            Session["viewState" + this.Context.Request.FilePath] = viewState;
            base.SavePageStateToPersistenceMedium(viewState);
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            if (Session["viewState" + this.Context.Request.FilePath] != null)
            {
                return Session["viewState" + this.Context.Request.FilePath];
            }
            return base.LoadPageStateFromPersistenceMedium();
        }


        protected override void OnPreInit(EventArgs e)
       {
            CreateBussniess(GetStringFromQueryString("entity", ""));
            base.OnPreInit(e);
        }

        ///// <summary>
        ///// 获取用户设置头象
        ///// </summary>
        ///// <param name="username">用户</param>
        ///// <returns>头像目录</returns>
        public static string GetAvater(string username)
        {
            string[] _ext = { "gif", "jpg", "png" };
            foreach (string ext in _ext)
            {
                if (System.IO.File.Exists(string.Format(HttpContext.Current.Request.PhysicalApplicationPath + "/Images/Pic/{0}.{1}", username, ext)))
                {
                    return string.Format("/images/pic/{0}.{1}", username, ext);
                }
            }
            return "";
        }
        /// <summary>
        /// 对应的编辑实体类
        /// </summary>
        public virtual string EditEntity
        {
            get
            {
                string query = GetStringFromQueryString("editentity", "");
                if (query != "")
                {
                    return query;
                }
                return EntityName.Replace("V_", "").Replace("v_", "");
            }
        }


        /// <summary>
        ///  实体ID
        /// </summary>
        public virtual string EntityId
        {
            get
            {
                return GetStringFromQueryString("entityid", "");
            }
        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _queryString = GetQueryString();
            if (this.Request.Url.ToString().Contains("/main.aspx") && (this.UserId) == null)
            {
                Response.Redirect("LoginOut.aspx");
            }
        }


        public HttpContext FLContext
        {
            get
            {
                return System.Web.HttpContext.Current;
            }
        }


        /// <summary>
        /// 签名
        /// </summary>
        public string Token
        {
            get
            {
                return FLContext.Session["token"] as string;
            }
        }

        /// <summary>
        /// 用于加载JS脚本使用
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string LoadPageString(string filePath)
        {
            System.IO.StringWriter sw = new StringWriter();
            FLContext.Server.Execute(filePath, sw);
            return sw.GetStringBuilder().ToString();
        }

        #region Account信息

        public bool IsAuthenticated
        {
            get { return HttpContext.Current.User.Identity.IsAuthenticated; }
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get { return HttpContext.Current.User.Identity.Name; }
        }

        /// <summary>
        /// 用户ID[]
        /// </summary>
        public Guid? UserId
        {
            get
            {
                if (User != null)
                {
                    return User.id;
                }
                else
                {
                    return null;
                }
            }
        }


        public int GetUserPasswordLimitDay()
        {
            return (new FL.Bussiness.Sys.BUser()).GetUserPasswordLimitDay(this.UserId);
        }


        public Guid? FunctionID
        {
            get
            {
                return GetGuidFromQueryString("functionid");
            }
        }


        public SysUser User
        {
            get
            {
                SysUser user = (Session["User"] as SysUser);
                //user.DBContext.DbConnention = "";
                if(user!=null)
                { 
                     user.password = "";
                }
                return user;
            }
        }



        public string UserJson
        {
            get
            {
                if (User != null)
                {
                    return FL.Common.Globals.getJSON(User);
                }
                else
                {
                    return "";
                }
            }
        }



        /// <summary>
        /// 断定当前的功能权限
        /// </summary>
        /// <returns></returns>
        public bool IsExistRight()
        {
            return false;
        }



        //在线试读功能 
        public string GetDefCondition()
        {
            return "1=1";
        }


        //判断网页浏览端
        public bool UserPoint()
        {

            string u = Request.ServerVariables["HTTP_USER_AGENT"];

            Regex b = new Regex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);

            Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);

            if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))//手机
            {
                return true;
            }
            else//电脑
                return false;

        }

        public string UserPointIP()
        {
            string ip = Request.ServerVariables["ip"];
            return ip;
        }


        /// <summary>
        /// 客户端IP
        /// </summary>
        public string ClientIP
        {
            get
            {
                string ip = "";
                if (Context.Request.ServerVariables["HTTP_VIA"] != null) // using proxy 
                {
                    ip = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP. 
                }
                else// not using proxy or can't get the Client IP 
                {
                    ip = Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP. 
                }
                return ip;
            }
        }


        #endregion

        #region URL Querystring 参数
        /// <summary>
        /// 获取参数集合
        /// </summary>
        /// <returns></returns>
        public NameValueCollection GetQueryString()
        {
            return new NameValueCollection(HttpContext.Current.Request.QueryString);
        }

        /// <summary>
        /// Allows access to QueryString values
        /// </summary>
        private NameValueCollection _queryString;
        public NameValueCollection QueryString
        {
            get
            {
                return GetQueryString();
            }
        }


        // *********************************************************************
        //  获取Guid参数
        /// <summary>
        /// Retrieves a value from the query string and returns it as an int.
        /// </summary>
        // ***********************************************************************/
        public Guid GetGuidFromQueryString(string key)
        {
            Guid returnValue = Guid.Empty;
            string queryStringValue;

            // Attempt to get the value from the query string
            //
            queryStringValue = QueryString[key];

            // If we didn't find anything, just return
            //
            if (queryStringValue == null)
                return returnValue;

            // Found a value, attempt to conver to integer
            //
            try
            {

                // Special case if we find a # in the value
                //
                if (queryStringValue.IndexOf("#") > 0)
                    queryStringValue = queryStringValue.Substring(0, queryStringValue.IndexOf("#"));

                returnValue = new Guid(queryStringValue);
            }
            catch { }

            return returnValue;

        }

        // *********************************************************************
        //  获取整型参数
        //
        /// <summary>
        /// Retrieves a value from the query string and returns it as an int.
        /// </summary>
        // ***********************************************************************/
        public int GetIntFromQueryString(string key, int defaultValue)
        {
            string queryStringValue;


            // Attempt to get the value from the query string
            //
            queryStringValue = this.QueryString[key];

            // If we didn't find anything, just return
            //
            if (queryStringValue == null)
                return defaultValue;

            // Found a value, attempt to conver to integer
            //
            try
            {

                // Special case if we find a # in the value
                //
                if (queryStringValue.IndexOf("#") > 0)
                    queryStringValue = queryStringValue.Substring(0, queryStringValue.IndexOf("#"));

                defaultValue = Convert.ToInt32(queryStringValue);
            }
            catch { }

            return defaultValue;

        }

        /// <summary>
        /// 获取字符参数
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public string GetStringFromQueryString(string key, string defaultValue)
        {
            string queryStringValue;


            // Attempt to get the value from the query string
            queryStringValue = this.QueryString[key];

            // If we didn't find anything, just return
            //
            if (queryStringValue == null)
                return defaultValue;

            return queryStringValue;

        }

        //public void WriteExpLog()
        //{
        //    Exception x = Server.GetLastError().GetBaseException();
        //    //LogBusiness buss = new LogBusiness();
        //    LogBusiness.WriteExceptionLog(x, this.User);
        //}


        #endregion

        public string CurrentHost
        {
            get
            {
                string host = Request.Url.Host;
                if (host.EndsWith("/")) host = host.Substring(0, host.Length - 1);
                host = "http://" + host + ":8001";
                //host = "http://" + host + ":7606";
                return host;
            }
        }
    }
}
